package com.xhtt.modules.inspection.schedule;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.xhtt.common.exception.RRException;
import com.xhtt.common.exception.RRExceptionEnum;
import com.xhtt.common.utils.DateUtils;
import com.xhtt.common.utils.EnumUtils;
import com.xhtt.modules.cfg.service.CfgWarnInsService;
import com.xhtt.modules.inspection.entity.InsTask;
import com.xhtt.modules.inspection.entity.InsTaskStep;
import com.xhtt.modules.inspection.entity.InsTaskUser;
import com.xhtt.modules.inspection.enums.InsPushEnum;
import com.xhtt.modules.inspection.enums.InspectTypeEnum;
import com.xhtt.modules.inspection.enums.ShiftTypeEnum;
import com.xhtt.modules.inspection.service.IInsTaskService;
import com.xhtt.modules.inspection.service.IInsTaskStepService;
import com.xhtt.modules.inspection.service.IInsTaskUserService;
import com.xhtt.modules.msg.entity.MsgInfo;
import com.xhtt.modules.msg.service.MsgUserService;
import com.xhtt.modules.sys.entity.SysUserDeptEntity;
import com.xhtt.modules.sys.entity.SysUserEntity;
import com.xhtt.modules.sys.service.SysUserDeptService;
import com.xhtt.modules.sys.service.SysUserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.scheduling.annotation.Schedules;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;

/**
 * @Date 2019/3/25 14:26
 **/
@Slf4j
@Component
public class InsTaskSchedule {

    @Autowired
    private IInsTaskService insTaskService;

    @Autowired
    private IInsTaskStepService insTaskStepService;

    @Autowired
    private IInsTaskUserService insTaskUserService;

    @Autowired
    private CfgWarnInsService cfgWarnInsService;

    @Autowired
    private SysUserService sysUserService;

    @Autowired
    private SysUserDeptService sysUserDeptService;

    @Autowired
    private MsgUserService msgUserService;


    /**
     * 消息表添加待巡检任务
     */
    @Scheduled(fixedDelay = 3 * 60 * 1000)
    public void pushInsTask() {

        // 获取待推送数据集合
        List<InsMsgEntity> insMsgEntities = insTaskStepService.pushList();

        if (CollectionUtils.isEmpty(insMsgEntities)) {
            return;
        }

        // 计数
        AtomicInteger i = new AtomicInteger();

        if (CollectionUtils.isNotEmpty(insMsgEntities)) {
            insMsgEntities.forEach(insMsgEntity -> {

                Integer taskId = insMsgEntity.getTaskId();
//                Integer teamId = insMsgEntity.getTeamId();
                InsTask insTask = insTaskService.getAllById(taskId);
                Integer shiftType = insMsgEntity.getShiftType();
                if (shiftType != null) {
                    if (shiftType.equals(ShiftTypeEnum.DAY.getCode())) {
                        insMsgEntity.setTime(DateUtils.tf.format(insTask.getInspectMorningStartDate()) + "-" + DateUtils.tf.format(insTask.getInspectMorningEndDate()));
                    } else if (shiftType.equals(ShiftTypeEnum.NIGHT.getCode())) {
                        insMsgEntity.setTime(DateUtils.tf.format(insTask.getInspectNightStartDate()) + "-" + DateUtils.tf.format(insTask.getInspectNightEndDate()));
                    }
                } else {
                    insMsgEntity.setTime(
                            DateUtils.tf.format(insTask.getInspectMorningStartDate()) + "-" +
                                    DateUtils.tf.format(insTask.getInspectMorningEndDate()) + "\t\t\t\t" +
                                    DateUtils.tf.format(insTask.getInspectNightStartDate()) + "-" +
                                    DateUtils.tf.format(insTask.getInspectNightEndDate()));
                }
                MsgInfo msgInfo = new MsgInfo();
                msgInfo.setMainType("安全巡检");
                msgInfo.setType("安全巡检");
                msgInfo.setTitle("有新巡检任务啦!");
                msgInfo.setContent(JSON.toJSONString(insMsgEntity));
                msgInfo.setRalateId(taskId);

                // 获取这个任务包含的所有人
                List<InsTaskUser> insTaskUsers = insTaskUserService.list(new LambdaQueryWrapper<InsTaskUser>().eq(InsTaskUser::getTaskId, taskId));
                if (CollectionUtils.isNotEmpty(insTaskUsers)) {
                    List<Integer> userIds = insTaskUsers.stream().map(InsTaskUser::getUserId).collect(Collectors.toList());
                    // 不需要添加组长
//                    SysUserEntity sysUserEntity = sysUserService.getTeamLeader(teamId);
//                    if (sysUserEntity == null) {
//                        log.error("没有组长");
//                    } else {
//                        // 添加组长id
//                        userIds.add(sysUserEntity.getUserId().intValue());
//                    }
                    // 添加人员消息关联表
                    userIds = userIds.stream().distinct().collect(Collectors.toList());
                    msgUserService.insertBatch(msgInfo, userIds);
                    i.getAndIncrement();
                    insTaskStepService.updatePushStatus(insMsgEntity.getTaskId(), insMsgEntity.getStep());
                }

            });
        }
        log.info("共添加" + i + "条消息");
    }


    /**
     * 巡检报警
     */
    @Scheduled(fixedDelay = 3 * 60 * 1000)
    public void pushOverTime() {
        List<InsMsgEntity> insMsgEntities = cfgWarnInsService.pushList();

        // 保存数据至消息表
        MsgInfo msgInfo = new MsgInfo();
        msgInfo.setMainType("报警提示");
        msgInfo.setType("安全巡检");
        msgInfo.setTitle("现场巡检任务超时未完成!");
        insMsgEntities.forEach(insMsgEntity -> {
            Integer userId = insMsgEntity.getUserId();
            msgInfo.setContent(JSON.toJSONString(insMsgEntity));
            msgInfo.setRalateId(insMsgEntity.getTaskId());

            List<Integer> userIds = new ArrayList<>();
            // 添加自己
            userIds.add(userId);
            // 添加组长
            SysUserEntity sysUserEntity = sysUserService.getTeamLeaderByUser(userId);
            if (sysUserEntity == null) {
                throw new RRException(RRExceptionEnum.NO_TEAM_LEADER);
            }
            userIds.add(sysUserEntity.getUserId().intValue());
            // 添加部门管理员
            SysUserEntity userEntity = sysUserService.getById(userId);
            List<SysUserEntity> deptLeaderList;
            if (userEntity.getTeamId() != null) {
                deptLeaderList = sysUserService.getDeptLeaderByTeam(userEntity.getTeamId());
            } else {
                Integer deptId = sysUserDeptService.getOne(new LambdaQueryWrapper<SysUserDeptEntity>().eq(SysUserDeptEntity::getUserId, userId)).getDeptId().intValue();
                deptLeaderList = sysUserService.getDeptLeaderByDept(deptId);
            }
            deptLeaderList.forEach(deptLeader -> userIds.add(deptLeader.getUserId().intValue()));

            msgUserService.insertBatch(msgInfo, userIds);
        });

        // 修改任务子表报警推送状态
        List<Integer> taskStepIds = insMsgEntities.stream().map(InsMsgEntity::getTaskStepId).collect(Collectors.toList());
        InsTaskStep insTaskStep = new InsTaskStep();
        insTaskStep.setPushed2(InsPushEnum.Y.getCode());
        if (CollectionUtils.isNotEmpty(taskStepIds)) {
            insTaskStepService.update(insTaskStep, new LambdaQueryWrapper<InsTaskStep>().in(InsTaskStep::getId, taskStepIds));
        }
    }
}
